<template>
  <div>
    <el-tree
        ref="treeRef"
        :data="componentTreeData"
        node-key="id"
        default-expand-all
        highlight-current
        @node-click="handleNodeClick"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span class="node-label">{{ formatComponent(data) }}</span>
          <span class="node-component-type">{{ formatComponentType(data) }}</span>
        </span>
      </template>
    </el-tree>
  </div>
</template>

<script lang="ts" setup>
import { watch, ref, inject, nextTick } from "vue";
import { vFormSchemeKey, vFormActiveElementKey } from '@/components/form/state.key';
import { InputComponents, ContainerComponents, TableComponents, LayoutComponents } from "../../../form/designer/data";
import type { ElTree } from 'element-plus'

const treeRef = ref<InstanceType<typeof ElTree>>()

const formScheme = inject(vFormSchemeKey)!
const vFormActiveElement = inject(vFormActiveElementKey)

interface Emits {
  (e: 'change', selectVariable: string): void
}

const emits = defineEmits<Emits>()

const componentTreeData = ref<any[]>([]);
const selectedId = ref('');

watch(() => formScheme, (val) => {
  componentTreeData.value = buildTree(formScheme.value, '');
}, { immediate: true, deep: true })

watch(() => vFormActiveElement, (val) => {
  setCurrentNode()
}, { immediate: true, deep: true })

/**
 * 根据激活对象设置当前节点
 */
function setCurrentNode() {
  nextTick(() => {
    if (vFormActiveElement.value && treeRef.value) {
      const nodeId = findNodeIdByElement(componentTreeData.value, vFormActiveElement.value)
      if (nodeId) {
        treeRef.value.setCurrentKey(nodeId)
      } else {
        treeRef.value.setCurrentKey(null)
      }
    } else if (treeRef.value) {
      treeRef.value.setCurrentKey(null)
    }
  })
}

/**
 * 根据element查找对应的节点ID
 */
function findNodeIdByElement(nodes: any[], element: any): string | null {
  for (const node of nodes) {
    if (node.element === element) {
      return node.id
    }
    if (node.children) {
      const foundId = findNodeIdByElement(node.children, element)
      if (foundId) {
        return foundId
      }
    }
  }
  return null
}

/**
 * 构造树结构,暂时只实现一层下级
 * @param schema
 * @param parentName
 */
function buildTree(schema: any, parentName: string): any[] {
  //搜索所有下级：非布局，展示，按钮组件
  let returnData = [];
  const childrens = schema.children || [];

  //遍历所有子节点
  for (let i = 0; i < childrens.length; i++) {
    if (childrens[i].category !== 'layout' && childrens[i].category !== 'display'
        && childrens[i].category !== 'button') {
      let tempNode: any = {};
      if (childrens[i].category == 'container' || childrens[i].component == 'ruoyi-ag-grid') {
        tempNode = {
          id: childrens[i].id,
          label: childrens[i].attrs?.title,
          component: childrens[i].component,
          element: childrens[i],
        }
        returnData.push(tempNode)
        let childReturnData = [];
        if (childrens[i].component == 'ruoyi-ag-grid') {
          // childReturnData = buildColumnDef(childrens[i]);
        } else {
          childReturnData = buildTree(childrens[i], childrens[i].name);
        }
        if (childReturnData.length > 0) {
          tempNode.children = childReturnData;
        }
      } else {
        returnData.push({
          id: childrens[i].id,
          label: childrens[i].formItemAttrs?.label,
          component: childrens[i].component,
          element: childrens[i],
        })
      }
    } else {
      let childReturnData = buildTree(childrens[i], childrens[i].name);

      let tempNode: any = {
        id: childrens[i].id,
        label: childrens[i].formItemAttrs ? childrens[i].formItemAttrs.label : childrens[i].component,
        component: childrens[i].component,
        element: childrens[i],
        children: []
      };
      if (childReturnData.length > 0) {
        tempNode.children = childReturnData;
      }
      returnData.push(tempNode)
    }
  }
  return returnData;
}

/**
 * 构造指定表的列列表
 * @param agGrid
 */
function buildColumnDef(agGrid: any) {
  //循环表格字段列表
  let columnDef = [];

  for (let i = 0; i < agGrid.attrs.columnDefs.length; i++) {
    let tempNode = {
      id: agGrid.attrs.columnDefs[i].field,
      label: agGrid.attrs.columnDefs[i].headerName,
      component: 'ruoyi-ag-grid-field',
    }
    columnDef.push(tempNode)
  }
  return columnDef;
}

/**
 * 单击某节点
 * @param data
 */
function handleNodeClick(data: any) {
  vFormActiveElement!.value = data.element;
}

/**
 * 翻译组件
 */
function formatComponent(row: any) {
  if (row.label === 'el-row') {
    return '布局行';
  } else if (row.label === 'el-col') {
    return '布局列';
  } else if (row.label === 'ruoyi-ag-grid-field') {
    return '表单组件';
  } else {
    return row.label;
  }
}

/**
 * 翻译组件类型
 * @param row
 * @returns {*|string}
 */
function formatComponentType(row: any) {
  // console.log('row.component:'+row.component)
  // console.log('InputComponents:'+JSON.stringify(InputComponents))
  for (let i = 0; i < InputComponents.length; i++) {
    if (row.component === InputComponents[i].component) {
      return InputComponents[i].title;
    }
  }
  for (let i = 0; i < ContainerComponents.length; i++) {
    if (row.component === ContainerComponents[i].component) {
      return ContainerComponents[i].title;
    }
  }
  for (let i = 0; i < TableComponents.length; i++) {
    if (row.component === TableComponents[i].component) {
      return TableComponents[i].title;
    }
  }
  for (let i = 0; i < LayoutComponents.length; i++) {
    if (row.component === LayoutComponents[i].component) {
      return LayoutComponents[i].title;
    }
    //查找下级
    if (LayoutComponents[i].children) {
      for (let j = 0; j < LayoutComponents[i].children.length; j++) {
        if (row.component === LayoutComponents[i].children[j].component) {
          return LayoutComponents[i].children[j].title;
        }
        if (LayoutComponents[i].children[j].children) {
          for (let k = 0; k < LayoutComponents[i].children[j].children.length; k++) {
            if (row.component === LayoutComponents[i].children[j].children[k].component) {
              return LayoutComponents[i].children[j].children[k].title;
            }
          }
        }
      }
    }
  }
  if (row.component === 'ruoyi-ag-grid-field') {
    return '列';
  }
  return '';
}
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.node-label {
  margin-right: 10px;
}

.node-component-type {
  color: #999;
  font-size: 12px;
}
</style>
